
using System.ComponentModel.DataAnnotations;
using Identity.Application.Contracts.Requests.Role;
using Identity.Application.Roles.Commands;
using Identity.HttpAPI.Permission;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace Identity.HttpAPI.Controllers
{
    [Authorize]
    [ApiController]
    [Route("api/roles")]
    public class RoleController : ControllerBase
    {
        private readonly IMediator _mediator;
        public RoleController(IMediator mediator)
        {
            _mediator = mediator;
        }


        [HttpPost]
        [Authorize(Policy = "role:item:create")]
        [Permission("role:item:create", "创建角色")]
        public async Task<IActionResult> CreateRoleAsync([FromBody] CreateRoleRequest req)
        {
            var command = new CreateRoleCommand(req.roleCode, req.roleName, req.description, req.status);
            var result = await _mediator.Send(command);

            return Ok(result);
        }


        [HttpDelete("{roleId}")]
        [Authorize(Policy = "Role.Delete")]
        [Permission("role:item:delete", "删除角色")]
        public async Task<IActionResult> DeleteRoleAsync(Guid roleId)
        {
            var command = new DeleteRoleCommand(roleId);
            await _mediator.Send(command);

            return NoContent();
        }


        [HttpGet]
        [Authorize(Roles = "Admin")]
        [Permission("role:items:Get", "获取全部角色")]
        public async Task<IActionResult> GetAllRoleAsync()
        {
            var command = new GetAllRoleCommand();
            var result = await _mediator.Send(command);

            return Ok(result);
        }


        [HttpGet("{roleId}")]
        [Authorize(Policy = "role:item:get")]
        [Permission("role:item:get", "获取角色")]
        public async Task<IActionResult> GetRoleByIdAsync(Guid roleId)
        {
            var command = new GetRoleByIdCommand(roleId);
            var result = await _mediator.Send(command);

            return Ok(result);
        }

        [HttpPut("{roleId}")]
        [Authorize(Policy = "Permission")]
        [Permission("role:item:update", "更新角色")]
        public async Task<IActionResult> UpdateRoleAsync(Guid roleId,[FromBody] UpdateRoleRequest rq)
        {
            var command = new UpdateRoleCommand(roleId,rq.roleCode,rq.roleName,rq.description,rq.status);
            var result = await _mediator.Send(command);
            return Ok(result);
        }


        [HttpPatch("{roleId}/change-roleName")]
        [Authorize(Policy = "role:item:name:update")]
        [Permission("role:item:name:update", "更新角色名称")]
        public async Task<IActionResult> UpdateRoleNameAsync(Guid roleId, [FromBody] ChangeRoleNameRequest req)
        {
            var command = new UpdateRoleNameCommand(roleId, req.newRoleName);
            var result = await _mediator.Send(command);

            return Ok(result);
        }

    }

}